package com.jevoly.listener;

import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;

public class DirectoryMonitor {

    private static Log log = LogFactory.getLog(DirectoryMonitor.class);

    FileAlterationMonitor monitor = null;

    public DirectoryMonitor(long interval) throws Exception {
        monitor = new FileAlterationMonitor(interval);
    }

    /**
     * 监控方法
     * @param path
     * @param listener
     */
    public void monitor(String path, FileAlterationListener listener) {
        FileAlterationObserver observer = new FileAlterationObserver(new File(path));
        monitor.addObserver(observer);
        observer.addListener(listener);
    }

    /**
     * 监控停止
     * @throws Exception
     */
    public void stop() throws Exception {
        monitor.stop();
    }

    /**
     * 监控开始
     * @throws Exception
     */
    public void start() throws Exception {
        monitor.start();
    }
}
 